'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async index() {
      console.log( this.ctx.session );
      if( !this.ctx.session.user ) {
          console.log( 'redirect to  login.html' );
          //this.ctx.redirect( '/public/login.html' );
          this.ctx.redirect( '/login.html' )
      }
      else {
          this.ctx.redirect( '/security.html' )
      }
  }
  async configdev_main() {
      console.log( this.ctx.session );
      if( !this.ctx.session.user ) {
          console.log( 'redirect to  login.html' );
          //this.ctx.redirect( '/public/login.html' );
          this.ctx.redirect( '/login.html' )
      }
      else {
          this.ctx.redirect( '/configdev.html' )
      }
  }

  async security_main() {
      console.log( this.ctx.session );
      if( !this.ctx.session.user ) {
          console.log( 'redirect to  login.html' );
          //this.ctx.redirect( '/public/login.html' );
          this.ctx.redirect( '/login.html' )
      }
      else {
          this.ctx.redirect( '/security.html' )
      }
  }

  async login( ) {
      var data = this.ctx.request.body;
      var phone = data.phone;
      var password = data.password;

      console.log( 'phone: ', phone, ' password: ', password );
      //vret = this.ctx.app.db.query( 'select * from admin_user WHERE mobile_phone = $1 and password = $2 ', [ phone, password ] );

      //var ret = await this.ctx.app.db.query( 'SELECT * FROM admin_user WHERE mobile_phone = $1 AND password = $2', [ phone, password ] );
      	try{
      	  var ret ;
      	  ret = await this.ctx.app.db.query( 'SELECT * FROM admin_user WHERE mobile_phone = $1', [ phone ] );
          if( ret.length > 0 ) {
              var user = ret[0];
              console.log( user );

              if( user.password == password ) {
			console.log('verify  success' );
			this.ctx.session.maxAge = 3600 * 24 * 1000;
                        this.ctx.session.user = ret[0];
                        this.ctx.session.save();
                        console.log( this.ctx.session );

			            this.ctx.status = 200;
                        this.ctx.body = { success:  '/security.html' } ;
            	}
            	else {
			        console.log('verify failed' );
            	    this.ctx.status = 404;
            	    his.ctx.body = { password_error: '密码错误' };
            	}
          }
          else {
              this.ctx.status = 404;
              this.ctx.body = { phone_error: '电话号码错误'};
          }
    	}
      catch( error ) {
		this.ctx.status = 404;
		this.ctx.body = { error: '服务器内部错误 ' + JSON.stringify( error )  };
     }
   }
}

module.exports = HomeController;
